package crud.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import crud.bean.Employee;
import crud.bean.Msg;
import crud.service.EmployeeService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理员工crud请求
 * @Author Bai Xu
 * @Date 2021/8/6 13:17
 * @Version 1.0
 */
@Controller
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    /**
     * 查询所有员工
     * @param pn
     * @param model
     * @return
     */
    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmpsWithJson(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model){
        PageHelper.startPage(pn, 5);
        List<Employee> employees = employeeService.getAll();
        PageInfo pageInfo = new PageInfo(employees);
        return Msg.success().add("page", pageInfo);
    }

    /**
     * 保存员工,并且使用JSR303进行后端校验
     * @param employee
     * @return
     */
    @RequestMapping(value = "/emp",method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result){
        if (result.hasErrors()){
            //校验失败，返回失败,在模态框中显示校验失败的错误信息
            Map<String,Object> map=new HashMap<>();

            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                System.out.println("错误的字段名"+fieldError.getField());
                System.out.println("错误信息"+fieldError.getDefaultMessage());
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            return Msg.fail().add("errorField", map);
        }else {
            employeeService.saveEmp(employee);
            return Msg.success();

        }
    }

    /**
     * 检查用户名是否可用
     * @param empName
     * @return
     */

    @RequestMapping("/checkUser")
    @ResponseBody
    public Msg checkUser(@RequestParam("empName") String empName){
     boolean b= employeeService.checkUser(empName);
     if (b){
         return Msg.success();
     }else {
         return Msg.fail();
     }

    }

    /**
     * 根据id查询员工信息
     * @param id
     * @return
     */
    @RequestMapping(value = "emp/{id}",method = RequestMethod.GET)
    @ResponseBody
       public Msg getEmp(@PathVariable("id") Integer id){
        Employee employee=  employeeService.getEmp(id);
        return Msg.success().add("emp", employee);

    }

    /**
     * 如果直接发送ajax=PUT请求，封装的数据除了路径上带了的，其他全是null
     *   问题：
     *   请求体中有数据，但是Employee封装不上
     *   update t_emp where emp_id=1024
     *   原因：
     *     Tomcat
     *       1.将请求体中的数据，封装成一个map
     *       2.request.getParameter("empName")就会从map中取值
     *       3.SpringMVC封装成POJO对象的时候，会把每个属性的值。request.getParameter("empName");
     *     AJAX请求不能直接发
     *      PUT请求中的数据request.getParameter("empName")拿不到
     *      Tomcat一看是put请求，就不会封装数据，只有post才会封装
     *    解决：
     *     我们要能支持直接发送PUT请求还要封装请求体中的数据
     *     配置上httpPutFormContentFilter
     *      他的作用：将请求体中的数据解析包装成一个map
     *      request被重新包装，request.getParameter()被重写，就会从自己封装的map取数据
     * 员工更新方法
     * @param employee
     * @return
     */
    @RequestMapping(value = "/emp/{empId}",method = RequestMethod.PUT)
    @ResponseBody
    public Msg UpdateEmp(Employee employee){
        System.out.println("将要更新的员工数据:"+employee);
        employeeService.updateEmp(employee);
        return Msg.success();
    }

    /**
     * 单个批量二合一
     *  批量删除：1-2-3
     *  单个删除：1
     * @param id
     * @return
     */
    @RequestMapping(value = "/emp/{ids}",method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteEmp(@PathVariable("ids")String ids){
        if (ids.contains("-")){
            List<Integer> del_ids=new ArrayList<>();
            //批量删除
            String[] str_ids = ids.split("-");
            //组装id集合
            for (String id : str_ids) {
                del_ids.add( Integer.parseInt(id));
            }
            employeeService.deleteBatch(del_ids);
        }else {
            //单个删除
            int id = Integer.parseInt(ids);
            employeeService.deleteEmp(id);
        }
        return Msg.success();
    }

    /*public String getEmps(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model){
        PageHelper.startPage(pn, 5);
        List<Employee> employees = employeeService.getAll();
        PageInfo pageInfo = new PageInfo(employees);
        model.addAttribute("page", pageInfo);
        return "list";
    }*/


}
